<template>
  <div 
    v-if="visible" 
    class="context-menu"
    :style="{ left: x + 'px', top: y + 'px' }"
    @contextmenu.prevent
  >
    <div class="menu-item" @click="handleEnterFolder" v-if="canEnterFolder">
      <span class="icon"><SvgIcon name="folder" :size="16" /></span>
      进入文件夹
    </div>
    <div class="menu-divider" v-if="canEnterFolder"></div>
    <div class="menu-item" @click="handleNewFolder">
      <span class="icon"><SvgIcon name="add" :size="16" /></span>
      新建文件夹
    </div>
    <div class="menu-item" @click="handleUploadFile">
      <span class="icon"><SvgIcon name="upload-file" :size="16" /></span>
      上传文件
    </div>
    <div class="menu-item" @click="handleUploadFolder">
      <span class="icon"><SvgIcon name="upload-folder" :size="16" /></span>
      上传文件夹
    </div>
    <div class="menu-divider"></div>
    <div class="menu-item" @click="handleRefresh">
      <span class="icon"><SvgIcon name="refresh" :size="16" /></span>
      刷新
    </div>
    <template v-if="selectedItems.length > 0">
      <div class="menu-divider"></div>
      <div class="menu-item" @click="handleDownload" v-if="canDownload">
        <span class="icon"><SvgIcon name="download" :size="16" /></span>
        {{ downloadText }}
      </div>
      <div class="menu-item" @click="handleCopyDownloadLink" v-if="canDownload && selectedItems.length === 1">
        <span class="icon"><SvgIcon name="link" :size="16" /></span>
        复制下载地址
      </div>
      <div class="menu-item" @click="handleRename" v-if="selectedItems.length === 1">
        <span class="icon"><SvgIcon name="edit" :size="16" /></span>
        重命名
      </div>
      <div class="menu-item danger" @click="handleDelete">
        <span class="icon"><SvgIcon name="delete" :size="16" /></span>
        {{ deleteText }}
      </div>
    </template>
  </div>
  
  <!-- 隐藏的文件上传输入框 -->
  <input 
    ref="fileInput" 
    type="file" 
    multiple 
    @change="onFileSelect"
    style="display: none"
  />
  <input 
    ref="folderInput" 
    type="file" 
    webkitdirectory 
    directory
    multiple 
    @change="onFolderSelect"
    style="display: none"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { FileItem } from '../api/fileService'
import { downloadFile } from '../api/fileService'
import { copyToClipboard } from '../utils'
import SvgIcon from './SvgIcon.vue'

interface Props {
  visible: boolean
  x: number
  y: number
  selectedItems: FileItem[]
}

interface Emits {
  (e: 'close'): void
  (e: 'newFolder'): void
  (e: 'upload', files: File[]): void
  (e: 'refresh'): void
  (e: 'delete', items: FileItem[]): void
  (e: 'rename', item: FileItem): void
  (e: 'enterFolder', item: FileItem): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const fileInput = ref<HTMLInputElement>()
const folderInput = ref<HTMLInputElement>()

// 是否可以下载（只有选中的都是文件才能下载）
const canDownload = computed(() => {
  return props.selectedItems.length > 0 && 
         props.selectedItems.some(item => item.type === 'file')
})

// 获取可下载的文件
const downloadableFiles = computed(() => {
  return props.selectedItems.filter(item => item.type === 'file')
})

// 是否可以进入文件夹（只选中一个文件夹）
const canEnterFolder = computed(() => {
  return props.selectedItems.length === 1 && 
         props.selectedItems[0].type === 'folder'
})

const handleEnterFolder = () => {
  if (props.selectedItems.length === 1 && props.selectedItems[0].type === 'folder') {
    emit('enterFolder', props.selectedItems[0])
  }
  emit('close')
}

const handleNewFolder = () => {
  emit('newFolder')
  emit('close')
}

const handleUploadFile = () => {
  fileInput.value?.click()
  emit('close')
}

const handleUploadFolder = () => {
  folderInput.value?.click()
  emit('close')
}

const handleRefresh = () => {
  emit('refresh')
  emit('close')
}

const handleDownload = () => {
  const filesToDownload = downloadableFiles.value
  
  if (filesToDownload.length === 1) {
    // 单个文件直接下载
    const item = filesToDownload[0]
    window.open(downloadFile(item.path), '_blank')
  } else {
    // 多个文件分别下载
    filesToDownload.forEach(item => {
      window.open(downloadFile(item.path), '_blank')
    })
  }
  emit('close')
}

const handleCopyDownloadLink = async () => {
  if (props.selectedItems.length === 1) {
    const item = props.selectedItems[0]
    const link = `${window.location.origin}${downloadFile(item.path)}`
    const success = await copyToClipboard(link)
    if (success) {
      alert('下载地址已复制到剪贴板')
    } else {
      alert('复制失败')
    }
  }
  emit('close')
}

const handleRename = () => {
  if (props.selectedItems.length === 1) {
    emit('rename', props.selectedItems[0])
  }
  emit('close')
}

const handleDelete = () => {
  emit('delete', props.selectedItems)
  emit('close')
}

const onFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    const files = Array.from(target.files)
    emit('upload', files)
    target.value = '' // 清空输入框，允许重复选择同一文件
  }
}

const onFolderSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    const files = Array.from(target.files)
    emit('upload', files)
    target.value = '' // 清空输入框
  }
}

const downloadText = computed(() => {
  const fileCount = downloadableFiles.value.length
  if (fileCount === 1) {
    return '下载'
  } else if (fileCount > 1) {
    return `批量下载 (${fileCount}个文件)`
  } else {
    return '下载'
  }
})

const deleteText = computed(() => {
  return props.selectedItems.length === 1 ? '删除' : '批量删除'
})
</script>

<style lang="less" scoped>
.context-menu {
  position: fixed;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(229, 231, 235, 0.8);
  border-radius: 10px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 
              0 10px 10px -5px rgba(0, 0, 0, 0.04),
              0 0 0 1px rgba(255, 255, 255, 0.5);
  z-index: 1000;
  min-width: 200px;
  padding: 6px;
  font-size: 14px;
  font-weight: 400;
  overflow: hidden;
  
  .menu-item {
    display: flex;
    align-items: center;
    padding: 10px 12px;
    cursor: pointer;
    user-select: none;
    transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
    border-radius: 6px;
    color: #374151;
    margin: 1px 0;
    
    &:hover {
      background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
      color: #1f2937;
      transform: translateX(2px);
    }
    
    &.danger {
      color: #dc2626;
      
      &:hover {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        color: #b91c1c;
      }
      
      .icon {
        opacity: 0.8;
      }
    }
    
    .icon {
      margin-right: 10px;
      width: 18px;
      height: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      opacity: 0.7;
      transition: opacity 0.15s ease;
    }
    
    &:hover .icon {
      opacity: 1;
    }
  }
  
  .menu-divider {
    height: 1px;
    background: linear-gradient(90deg, transparent, #e5e7eb, transparent);
    margin: 6px 8px;
    opacity: 0.8;
  }
  
  // 进入动画
  animation: contextMenuIn 0.15s cubic-bezier(0.4, 0, 0.2, 1);
  
  @keyframes contextMenuIn {
    from {
      opacity: 0;
      transform: scale(0.95) translateY(-4px);
    }
    to {
      opacity: 1;
      transform: scale(1) translateY(0);
    }
  }
}

// 移动端优化
@media (max-width: 768px) {
  .context-menu {
    min-width: 220px;
    padding: 8px;
    border-radius: 12px;
    
    .menu-item {
      padding: 14px 16px;
      border-radius: 8px;
      font-size: 15px;
      
      .icon {
        width: 20px;
        height: 20px;
        font-size: 16px;
        margin-right: 12px;
      }
    }
    
    .menu-divider {
      margin: 8px 12px;
    }
  }
}

@media (max-width: 480px) {
  .context-menu {
    min-width: 200px;
    
    .menu-item {
      padding: 16px 18px;
      font-size: 14px;
    }
  }
}
</style> 